/**
 * @description 注册表-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require('fs')
const ox = require('@daelui/oxjs')
const Service = require('./service.js')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 同步环境
  */
  syncEnvir (action) {
    // 解析数据
    return this.solveAction(action).then(async action => {
      let params = action.params || {}
      // 查询所有的文件数据
      let list = await this.$service.queryAll({
        params: {
          status: '1'
        },
        excute: {
          operators: [
            {field: 'status', operator: 'EQUAL'}
          ],
          sort: [
            {field: 'createTime', by: 'desc'},
            {field: 'order', by: 'desc'}
          ]
        }
      })
      list = list.data
      list = Array.isArray(list) ? list : []
      list = list.map(item => {
        let node = {
          name: item.name,
          version: item.version,
          path: item.path,
          type: item.type,
          text: item.text
        }
        let deps = []
        if (item.deps) {
          try {
            deps = JSON.parse(item.deps)
            deps = Array.isArray(deps) ? deps : []
            deps = deps.filter(item => {
              return !!item.path
            })
            deps = deps.map(item => {
              return item.path
            })
          } catch (e) {}
        }
        if (deps && deps.length) {
          node.deps = deps
        }
        return node
      })
      let constant = this.route.scope.CONFIG.constant
      let path = constant.poolPath + '/prod'
      if (!fs.existsSync(path)) {
        filer.buildPath(path)
      }
      path += '/components.json'
      let success = 0
      // 文件写入
      try {
        let content = JSON.stringify(list, null, ' ')
        fs.writeFileSync(
          path, content
        )
        success = 1
      } catch (e) {
        success = 0
      }
      return {data: list, success: 1}
    })
  }
}

module.exports = Controller